import 'dart:io';

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

import '../provider/AuthProvider.dart';
import '../provider/UserProvider.dart';
import '../utils/api.dart';
import 'GenderSelectionPage.dart';

class MyPage extends StatefulWidget {
  const MyPage({super.key});

  @override
  State<MyPage> createState() => _UserProfilePageState();
}

class _UserProfilePageState extends State<MyPage> {
  final _nicknameController = TextEditingController();
  String? _userId;
  int _gender = 0; // 1男，2女

  @override
  void initState() {
    super.initState();
    _userId = context.read<AuthProvider>().userId;
    if (_userId != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        context.read<UserProvider>().fetchUserInfo(_userId!);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final userProvider = context.watch<UserProvider>();
    final authProvider = context.read<AuthProvider>();

    if (userProvider.loading) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }

    _nicknameController.text = userProvider.nickname ?? '';
    _gender = userProvider.gender ?? 0;

    String genderText(int g) {
      switch (g) {
        case 0:
          return '男';
        case 1:
          return '女';
        default:
          return '男'; // 默认显示男
      }
    }

    return Scaffold(
      appBar: AppBar(title: const Text('个人资料')),
      backgroundColor: const Color(0xFFF5F5F5),
      body: Column(
        children: [
          const SizedBox(height: 10),

          Container(
            color: Colors.white,
            child: Column(
              children: [
                ListTile(
                  title: const Text('头像'),
                  trailing: CircleAvatar(
                    radius: 22,
                    backgroundImage: userProvider.avatarUrl != null
                        ? NetworkImage(userProvider.avatarUrl!)
                        : null,
                    child: userProvider.avatarUrl == null
                        ? const Icon(Icons.person)
                        : null,
                  ),
                  onTap: _pickAvatar,
                ),
                const Divider(height: 1),
                ListTile(
                  title: const Text('昵称'),
                  trailing: Text(
                    userProvider.nickname ?? '',
                    style: const TextStyle(color: Colors.grey),
                  ),
                  onTap: () => _editNickname(),
                ),
                const Divider(height: 1),
                ListTile(
                  title: const Text('性别'),
                  trailing: Text(
                    genderText(userProvider.gender ?? 0),
                    style: const TextStyle(color: Colors.grey),
                  ),
                  onTap: () => _navigateToGenderPage(),
                ),
              ],
            ),
          ),

          const SizedBox(height: 20),

          // 新增“看一看” & “设置” 两个选项栏
          Container(
            color: Colors.white,
            child: Column(
              children: [
                ListTile(
                  title: const Text('看一看'),
                  trailing: const Icon(Icons.chevron_right),
                  onTap: () {
                    context.push('/explore'); // GoRouter 跳转示例
                  },
                ),
                const Divider(height: 1),
                ListTile(
                  title: const Text('设置'),
                  trailing: const Icon(Icons.chevron_right),
                  onTap: () {
                    context.push('/settings'); // GoRouter 跳转示例
                  },
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _pickAvatar() async {
    final picker = ImagePicker();
    final picked = await picker.pickImage(source: ImageSource.gallery);
    if (picked != null && _userId != null) {
      final url = await uploadAvatar(picked.path);
      await context.read<UserProvider>().updateAvatar(url, _userId!);
    }
  }

  void _editNickname() {
    showDialog(
      context: context,
      builder: (_) {
        final controller = TextEditingController(
          text: _nicknameController.text,
        );
        return AlertDialog(
          title: const Text('修改昵称'),
          content: TextField(controller: controller),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () async {
                final newName = controller.text.trim();
                if (_userId != null && newName.isNotEmpty) {
                  await context.read<UserProvider>().updateNickname(
                    newName,
                    _userId!,
                  );
                  setState(() {
                    _nicknameController.text = newName;
                  });
                }
                Navigator.pop(context);
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  Future<void> _navigateToGenderPage() async {
    final selected = await Navigator.push<int>(
      context,
      MaterialPageRoute(
        builder: (_) => GenderSelectionPage(currentGender: _gender),
      ),
    );
    if (selected != null && selected != _gender && _userId != null) {
      await context.read<UserProvider>().updateGender(selected, _userId!);
      setState(() {
        _gender = selected;
      });
    }
  }

  Future<String> uploadAvatar(String path) async {
    final file = File(path);
    final url = await Api.uploadImage(file);
    if (url == null) throw Exception('上传失败');
    return url;
  }
}
